package com.ywjh.inter.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywjh.inter.common.SystemConfig;
import com.ywjh.inter.entity.BindInsulinEntity;
import com.ywjh.inter.entity.DocProfileEntity;
import com.ywjh.inter.entity.InstitutionEntity;
import com.ywjh.inter.entity.ProfileEntity;
import com.ywjh.inter.entity.UsersEntity;
import com.ywjh.inter.entity.UsersHXEntity;
import com.ywjh.inter.service.HXService;
import com.ywjh.inter.service.InstService;
import com.ywjh.inter.service.InsulinService;
import com.ywjh.inter.service.UsersService;
import com.ywjh.inter.utils.PinyinUtils;
import com.ywjh.inter.utils.StrUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Friend extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2499373273872616108L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");

		JSONObject postData = StrUtil.getPostJSON(req);
		System.out.print(postData.toString());
		String act = postData.getString("act");
		JSONObject data = postData.getJSONObject("data");
		int r = 0;
		String e = "";
		JSONObject json = new JSONObject();
		switch (act) {
		case "list":
			int user_id = data.getInt("user_id");
			UsersHXEntity hx = UsersService.getInstance().findHXUserByUserId(user_id);
			if (hx == null) {
				e = "hx账户不存在";
			} else {
				JSONObject resultJson = HXService.getInstance().getFriendList(hx.getUsername(),
						HXService.getInstance().token());
				r = 1;
				JSONArray friendArray = resultJson.getJSONArray("data");
				JSONArray docArray = new JSONArray();
				JSONArray patientArray = new JSONArray();
				for (int i = 0; i < friendArray.size(); i++) {
					String hx_username = friendArray.getString(i);
					if (hx_username.indexOf("user_") > -1) {
						int friendID = Integer.parseInt(
								hx_username.substring(hx_username.lastIndexOf("_") + 1, hx_username.length()));
						UsersEntity friendEntity = UsersService.getInstance().findUserById(friendID);
						if (friendEntity != null) {
							switch (friendEntity.getIs_doc()) {
							case 1:
								DocProfileEntity docProfileEntity = UsersService.getInstance()
										.findDocProfileByUserId(friendID);
								JSONObject docJson = new JSONObject();
								docJson.put("head_url", SystemConfig.SERVER_DOMAIN + friendEntity.getHead_url());
								docJson.put("loginname", friendEntity.getLoginname());
								docJson.put("phone", friendEntity.getPhone());
								docJson.put("hx_username", hx_username);
								docJson.put("initial", "#");
								docJson.put("is_doc", 1);
								if (docProfileEntity != null) {
									String py = PinyinUtils.toPinyinString(docProfileEntity.getName());
									if (py != null && py.length() > 1) {
										docJson.put("initial", py.substring(0, 1).toUpperCase());
									}
									JSONObject profile = new JSONObject();
									profile.put("user_id", docProfileEntity.getUser_id());
									profile.put("name", docProfileEntity.getName());
									profile.put("title", docProfileEntity.getTitle());
									profile.put("inst_id", docProfileEntity.getInst_id());
									profile.put("good", docProfileEntity.getGood());
									profile.put("address", docProfileEntity.getAddress());
									profile.put("idcard", docProfileEntity.getIdcard());
									profile.put("nickname", docProfileEntity.getNickname());
									InstitutionEntity keshi = InstService.getInstance()
											.findById(docProfileEntity.getInst_id());
									if (keshi != null) {
										profile.put("keshi", keshi.getName());
										InstitutionEntity bumen = InstService.getInstance().findById(keshi.getPid());
										if (bumen != null) {
											profile.put("bumen", bumen.getName());
											InstitutionEntity yiyuan = InstService.getInstance()
													.findById(bumen.getPid());
											profile.put("yiyuan", yiyuan.getName());
										}
									}
									profile.put("memo", docProfileEntity.getMemo());
									profile.put("gender", docProfileEntity.getGender());
									profile.put("head_url", SystemConfig.SERVER_DOMAIN + friendEntity.getHead_url());
									docJson.put("profile", profile);
								}
								docArray.add(docJson);
								break;
							default:
								ProfileEntity profileEntity = UsersService.getInstance().getProfileByUserId(friendID);
								JSONObject patientJson = new JSONObject();
								patientJson.put("head_url", SystemConfig.SERVER_DOMAIN + friendEntity.getHead_url());
								patientJson.put("loginname", friendEntity.getLoginname());
								patientJson.put("phone", friendEntity.getPhone());
								patientJson.put("hx_username", hx_username);
								patientJson.put("initial", "#");
								patientJson.put("is_doc", 0);
								if (profileEntity != null) {
									String py = PinyinUtils.toPinyinString(profileEntity.getName());
									if (py != null && py.length() > 1) {
										patientJson.put("initial", py.substring(0, 1).toUpperCase());
									}
									BindInsulinEntity bindInsulinEntity= InsulinService.getInstance().findInsulinByPatientId(friendEntity.getId());
									patientJson.put("profile", profileEntity.toJson(friendEntity, bindInsulinEntity));
								}
								patientArray.add(patientJson);
								break;
							}
						} else {
							System.out.println("friend is null:" + friendID);
						}
					}
				}
				JSONObject d = new JSONObject();
				d.put("patient_list", patientArray);
				d.put("doc_list", docArray);
				json.put("d", d);
			}
			break;
		case "delete":
			user_id = data.getInt("user_id");
			int friend_id = data.getInt("friend_id");
			UsersHXEntity userHX = UsersService.getInstance().findHXUserByUserId(user_id);
			UsersHXEntity friendHX = UsersService.getInstance().findHXUserByUserId(friend_id);
			if (userHX == null) {
				e = "用户HX不存在";
				break;
			}
			if (friendHX == null) {
				e = "好友HX不存在";
				break;
			}
			JSONObject result = HXService.getInstance().deleteFriend(userHX.getUsername(), friendHX.getUsername(),
					HXService.getInstance().token());
			UsersService.getInstance().deleteFocus(user_id, friend_id);
			if (result != null) {
				r = 1;
			} else {
				e = "HX deleteFriend error.";
			}
		}
		json.put("r", r);
		json.put("e", e);
		PrintWriter pw = resp.getWriter();
		pw.write(json.toString());
		pw.flush();
		pw.close();
	}
}
